package com.atguigu.dga230301.governance.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ThreadDemo {
   static ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(100,100,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>());

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        System.out.println("开始："+ startTime);
        List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
        Integer sum = 0;
/*        for (Integer integer : integerList) {
            sum += integer * integer;
        }*/

        ArrayList<CompletableFuture<Integer>> futureArrayList = new ArrayList<>();
        for (Integer integer : integerList) {
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
                @Override
                public Integer get() {

                    return integer * integer;
                }
            },threadPoolExecutor);
            futureArrayList.add(completableFuture);
        }

        //将每个数字的计算结果集结
        List<Integer> integers = futureArrayList.stream().map(integerCompletableFuture -> integerCompletableFuture.join()).collect(Collectors.toList());

        for (Integer integer : integers) {
            sum += integer;
        }

        long endTime = System.currentTimeMillis();
        System.out.println("运行时间："+(endTime-startTime));
        System.out.println(sum);
    }
}
